package cn.kgc.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @author 课工场
 * @date 2024/6/3
 * @description  shiro中的权限控制
 */
public class TestAuthorizationInfo {

    public static void main(String[] args) {


        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        CustomerRealm realm = new CustomerRealm();
        // realm设置密码凭证匹配器
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        // 设置散列的次数
        md5.setHashIterations(10);
        realm.setCredentialsMatcher(md5);

        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);

        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken("admin","123456"));

        boolean authenticated = subject.isAuthenticated();
        System.out.println("authenticated = " + authenticated);


        //  认证通过之后 如何实现授权操作     基于角色   基于权限字符串       编程式   注解式
        //    /user/delete   admin    编程式角色权限控制

        // boolean b = subject.hasRole("admin");
        // boolean[]   包含那个角色  则对应的位置返回true
        // boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "super", "guster"));
        // for (boolean aBoolean : booleans) {
        //     System.out.println("aBoolean = " + aBoolean);
        // }
        // 必须同时包含所有的指定角色  true
        // boolean b = subject.hasAllRoles(Arrays.asList("admin", "super"));


        //  编程式权限字符串
        boolean b = subject.isPermitted("sys:user:delete");



        System.out.println("hasRole admin= " + b);
        if (b){
            System.out.println("删除数据");
        }else {
            System.out.println("没有权限,请联系管理员");
        }


    }
}
